package com.gxc.controller;

import com.alibaba.fastjson.JSONObject;
import com.gxc.entity.User;
import com.gxc.enums.LoginEnums;
import com.gxc.service.UserService;
import com.gxc.utils.RestControllerResult;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 登陆相关Controller.
 *
 * @author 宫新程
 * @since 2018/12/15 2:09 PM
 */
@Slf4j
@RestController
public class LoginController {

  @Resource private UserService userService;

  /** 登陆. */
  @PostMapping("/login")
  public RestControllerResult<String> login(User user, HttpServletRequest request) {
    RestControllerResult<String> result = new RestControllerResult<>();
    List<User> userList = userService.findUserByUsername(user.getUsername());
    if (userList.isEmpty()) {
      log.error("用户名不存在！参数：{}", JSONObject.toJSONString(user));
      result.setSuccess(false);
      result.setErrorMsg("用户名不存在！");
      return result;
    }
    User dbUser = userList.get(0);
    if (!user.getPassword().equals(dbUser.getPassword())) {
      log.error("密码错误！参数：{}", JSONObject.toJSONString(user));
      result.setSuccess(false);
      result.setErrorMsg("密码错误！");
      return result;
    }
    // 将登陆的用户信息放到session中.
    HttpSession session = request.getSession();
    session.setAttribute(LoginEnums.LOGIN_USER.getKey(), dbUser);

    result.setSuccess(true);
    result.setData("登陆成功！");
    return result;
  }

  /** 退出登陆. */
  @GetMapping("/logout")
  public RestControllerResult<Boolean> logout() {
    RestControllerResult<Boolean> result = new RestControllerResult<>();
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpSession session = requestAttributes.getRequest().getSession();
    session.invalidate();
    result.setSuccess(true);
    log.error("退出成功！");
    return result;
  }
}
